<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: Core.php 2010-08-31 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Page_Api_Core extends Core_Api_Abstract
{
	protected $_modules;
	
	public function getContentTable($type)
	{
		return Engine_Api::_()->getItemTable($type);
	}

	public function getNoPhoto($type)
	{
		return Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'home') .
						"application/modules/Page/externals/images/nophoto/" . $type . ".png";
	}
	
	public function shortenType($type)
	{
		$prefix = substr($type, 0, 4);
		if ($prefix == 'page'){
			return substr($type, 4);
		}

		return $type;
	}
	
	public function getPopularLocations()
	{
		$table = Engine_Api::_()->getDbTable('pages', 'page');
		$select = $table->select();
		$name = $table->info('name');
		
		$select
			->setIntegrityCheck(false)
			->from($name, array('city', 'count' => 'COUNT(city)'))
			->order('count DESC')
			->where('city IS NOT NULL AND city <> ""')
      ->where($name.'.approved = 1')
			->group('city')
			->limit(7);
			
		return $table->fetchAll($select)->toArray();
	}
	
	public function getPopularCategories() 
	{
		$table = Engine_Api::_()->getDbTable('pages', 'page');
		$select = $table->select();

    $prefix = $table->getTablePrefix();

		$select
			->setIntegrityCheck(false)
			->from($prefix.'page_fields_values', array('value', 'count' => 'COUNT(value)'))
			->joinLeft($prefix.'page_fields_options', $prefix.'page_fields_options.option_id = '.$prefix.'page_fields_values.value', array('category' => 'label'))
			->where($prefix.'page_fields_values.field_id = 1')
      ->joinLeft($prefix.'page_pages', $prefix.'page_fields_values.item_id = '.$prefix.'page_pages.page_id', array())
      ->where($prefix.'page_pages.approved = 1')
			->group($prefix.'page_fields_values.value')
			->order('count DESC')
			->limit(7);
			
		return $table->fetchAll($select)->toArray();
	}

	public function getCategorizedFieldIds()
	{
    $table = Engine_Api::_()->getDbTable('pages', 'page');
		$db = $table->getAdapter();
		$select = $db->select();
		$prefix = $table->getTablePrefix();

		$select
			->from($prefix.'page_fields_options', array('option_id'))
			->where($prefix.'page_fields_options.field_id = 1');
			
		$result = array();
		$option_ids = $db->fetchAll($select, array(), Zend_Db::FETCH_COLUMN);
		if (empty($option_ids)){
			return array();
		}
		
		$where = $prefix."page_fields_maps.option_id IN (".implode(',' , $option_ids).")";
		$select = $db->select();
		$select
			->from($prefix.'page_fields_maps', array('child_id', 'option_id'))
			->where($where);

		return $db->fetchPairs($select);
	}
	
	public function getPage($id)
	{
		if ($id instanceof Core_Model_Item_Abstract){
			return $id;
		}
		
		$pageTable = Engine_Api::_()->getDbTable('pages', 'page');
		$select = $pageTable->select()->where('url = ?', $id)->orWhere('page_id = ?', $id)->orWhere('name = ?', $id);
		return $pageTable->fetchRow($select);
	}
	
	public function getToday()
	{
		$timestamp = time();
		$today = getdate($timestamp);
		$month = $today['mon']; 
		$mday = $today['mday']; 
		$year = $today['year']; 
		return date('Y-m-d H:i:s', mktime(0, 0, 0, $month, $mday, $year));
	}
	
	public function getUsersForAdmin(array $params)
	{
		if (empty($params['page_id'])){
			return array();
		}

		$table = Engine_Api::_()->getDbTable('membership', 'page');
    $prefix = $table->getTablePrefix();
    
		$select = $table->select();
		$select
			->from($prefix.'page_membership', array('user_id'))
			->where('resource_id = ?', $params['page_id']);
			
		$user_ids = $table->getAdapter()->fetchCol($select);
		$user_ids[] = Engine_Api::_()->user()->getViewer()->getIdentity(); 
		
		$table = Engine_Api::_()->getItemTable('user');
		$select = $table->select();
		
		if (!empty($params['keyword'])){
			$select
				->where("username LIKE '%{$params['keyword']}%'")
				->orWhere("displayname LIKE '%{$params['keyword']}%'");
		}
		
		if (!empty($user_ids)){
			$user_ids = implode(',', $user_ids);
			$select
				->where("user_id NOT IN ({$user_ids})");
		}
		
		$paginator = Zend_Paginator::factory($select);
		$paginator->setItemCountPerPage(1);
		
		return $paginator;
	}
		
	public function getTags($params = array())
	{
    $table = Engine_Api::_()->getDbTable('pages', 'page');
		$db = $table->getAdapter();
		$select = $db->select();

    $prefix = $table->getTablePrefix();

		$select
			->from($prefix.'core_tagmaps', array('tag_id', 'page_id' => $prefix.'core_tagmaps.resource_id', 'freq' => 'COUNT('.$prefix.'core_tagmaps.tag_id)'))
			->joinLeft($prefix.'core_tags', $prefix.'core_tagmaps.tag_id = '.$prefix.'core_tags.tag_id', array('text'))
      ->joinLeft($prefix.'page_pages', $prefix.'core_tagmaps.resource_id = '.$prefix.'page_pages.page_id', array())
			->where($prefix."core_tagmaps.resource_type = 'page'")
      ->where($prefix."page_pages.approved = 1")
			->group($prefix.'core_tags.text');
		
		if (!empty($params['page_id'])){
			if (is_array($params['page_id'])){
				$where = $prefix."core_tagmaps.resource_id IN (".implode(',', $params['page_id']).")";
			}elseif (is_numeric($params['page_id'])){
				$where = $prefix."core_tagmaps.resource_id = {$params['page_id']}";
			}
			$select
				->where($where);
		}
		
		$rawData = $db->fetchAll($select);
		$type = '';
		if (!empty($params['categorized'])){
			$type = $params['categorized'];
		}
		
		return $this->categorizeTags($rawData, $type);
	}
	
  public function getPageTags(array $page_ids)
  {
    if (empty($page_ids)){
      return array();
    }

    $table = Engine_Api::_()->getDbTable('pages', 'page');
    $db = $table->getAdapter();
    $select = $db->select();

    $prefix = $table->getTablePrefix();
    
    $select
      ->from($prefix.'core_tagmaps', array('tag_id', 'page_id' => $prefix.'core_tagmaps.resource_id'))
      ->joinLeft($prefix.'core_tags', $prefix.'core_tagmaps.tag_id = '.$prefix.'core_tags.tag_id', array('text'))
      ->joinLeft($prefix.'page_pages', $prefix.'page_pages.page_id = '.$prefix.'core_tagmaps.resource_id', array())
      ->where($prefix."core_tagmaps.resource_type = 'page'")
      ->where($prefix."page_pages.approved = 1");
    
    if (!empty($page_ids)){
      $where = $prefix."core_tagmaps.resource_id IN (".implode(',', $page_ids).")";
      $select
        ->where($where);
    }
    
    $rawData = $db->fetchAll($select);
    
    return $this->categorizeTags($rawData, 'page');
  }
	
	public function categorizeTags($rawData, $type = '')
	{
		$tags = array();
		if ($type == 'page'){
			foreach ($rawData as $item){
				$tags[$item['page_id']][] = $this->defineTagClass($item);
			}
		}else{
			foreach ($rawData as $item){
				$tags[] = $this->defineTagClass($item);
			}
		}
		
		return $tags;
	}
	
	public function defineTagClass($tag)
	{
	  if (empty($tag['freq'])){
	    return $tag;
	  }
	  
		if ($tag['freq'] <= 1){
			$tag['class'] = 1;
		}elseif ($tag['freq'] <= 3){
			$tag['class'] = 2;
		}elseif ($tag['freq'] <= 7){
			$tag['class'] = 3;
		}elseif ($tag['freq'] <= 10){
			$tag['class'] = 4;
		}elseif ($tag['freq'] <= 20){
			$tag['class'] = 5;
		}elseif ($tag['freq'] <= 40){
			$tag['class'] = 6;
		}elseif ($tag['freq'] <= 65){
			$tag['class'] = 7;
		}elseif ($tag['freq'] <= 100){
			$tag['class'] = 8;
		}else{
			$tag['class'] = 9;
		}
		
		return $tag;
	}
	
	public function categorizedBy($item)
	{
		return $this->defineTagClass($item);
	}
	
	public function categorizedByPage($item, &$key)
	{
		$key = $item['page_id'];
		return array($key => $this->defineTagClass($item));
	}

	// @todo make following functions common
	public function truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
	{
		if ($length == 0)
			return '';
		
		if (strlen($string) > $length) {
			$length -= strlen($etc);
			if (!$break_words && !$middle) {
				$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
			}
			if(!$middle) {
				return substr($string, 0, $length).$etc;
			} else {
				return substr($string, 0, $length/2) . $etc . substr($string, -$length/2);
			}
		} else {
			return $string;
		}
	}

	public function isModuleExists($module)
	{
		if (!isset($this->_modules[$module])){
      $table = Engine_Api::_()->getDbTable('pages', 'page');
			$db = $table->getAdapter();
      $prefix = $table->getTablePrefix();
			$select = $db->select()->from($prefix.'core_modules', array('COUNT(*)'))->where('name = ?', $module);
      
			$this->_modules[$module] = (bool)$db->fetchOne($select);
		}
		
		return $this->_modules[$module];
	}

	public function isAllowedComment($pageObject)
	{
		return (bool)$pageObject->authorization()->isAllowed(Engine_Api::_()->user()->getViewer(), 'comment');
	}
	
	public function isAllowedPost($pageObject)
	{
		return (bool)$pageObject->authorization()->isAllowed(Engine_Api::_()->user()->getViewer(), 'posting');
	}
	
	public function isAllowedView($pageObject)
	{
		return (bool)$pageObject->authorization()->isAllowed(Engine_Api::_()->user()->getViewer(), 'view');
	}
	
	public function getFriends($params)
	{
		$viewer = Engine_Api::_()->user()->getViewer();
		$table = Engine_Api::_()->getItemTable('user');
    $prefix = $table->getTablePrefix();
    
		$select = $table->select()
			->setIntegrityCheck(false)
			->from($prefix.'users')
			->joinLeft($prefix.'user_membership', $prefix.'user_membership.user_id = '.$prefix.'users.user_id', array())
			->where($prefix.'user_membership.resource_id = ?', $viewer->getIdentity())
			->where($prefix.'user_membership.resource_approved = 1')
			->where($prefix.'user_membership.user_approved = 1');

		return Zend_Paginator::factory($select);
	}
	
}